package myservice.android.activities;

import myservice.android.Global;
import myservice.android.R;
import android.app.AlertDialog;
import android.content.DialogInterface;

/** 
 * Base activity for all MyService activities that have editable content, such as EditText and CheckBox.
 * Inherits {@link BaseActivity BaseActivity}.
 * 
 */
public abstract class BaseSaveableActivity extends BaseActivity {
		
	/** 
	 *  Specifies whether any content in this activity has been modified.
	 *  If set to true, the user will be asked to save the activity before navigating away
	 */	
	public boolean activityContentModified;					
	
    @Override
    public void onResume() {
    	super.onResume();
        activityContentModified = false;
    }	
    
    @Override
    public void onBackPressed() {
    	saveChangesCheck(true);
    }         
    
    /**
     * Checks if any changes have been made to activity contents.
     * If changes are made, asks the user to save the activity.
     * If changes are not made, does nothing.
     *  
     * @param close	if true, closes the activity upon positive answer to the prompt.
     */
    protected void saveChangesCheck(boolean close) {
    	
    	if (activityContentModified == true) {
    		        	
        	final boolean closeActivity = close;
        	
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
			alertDialogBuilder.setTitle(Global.res.getText(R.string.title_question));				
			alertDialogBuilder
				.setMessage(Global.res.getText(R.string.message_save_changes))
				.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						save();	
						if (closeActivity) {
							finish();
						}
					}
				  })
				.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						if (closeActivity) {
							finish();
						}
					}
				});
	 
			AlertDialog alertDialog = alertDialogBuilder.create();
			alertDialog.show();	  
    	} else {
			if (close) {
				finish();
			}	
    	}
    	
    }       
    
    /**
     * Here you must save all data to database.
     */
    protected void save() { }

}
